/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufpe.cin.dmo4.middleware.io;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 *
 * @author Danilo
 */
public class SocketChannelHandler {

    private final SocketChannel channel;

    public SocketChannelHandler(SocketChannel channel) {
        this.channel = channel;
    }

    public SocketChannel getChannel() {
        return channel;
    }

    public byte[] getBytes() throws IOException {
        ByteBuffer buf = ByteBuffer.allocateDirect(1024);

        try {
            // Clear the buffer and read bytes from socket
            buf.clear();
            int numBytesRead = channel.read(buf);

            if (numBytesRead == -1) {
                // No more bytes can be read from the channel
            } else {
                // To read the bytes, flip the buffer
                buf.flip();

                byte[] b = new byte[buf.remaining()];
                buf.get(b);

                return b;

            }
        } catch (IOException e) {
            throw e;
        }

        return null;
    }

    public void writeBytes(byte[] bytes) throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(bytes.length);
        buf.clear();
        buf.put(bytes);

        buf.flip();

        while (buf.hasRemaining()) {
            channel.write(buf);
        }
    }

}
